package com.xy.job.executor.core.job

import java.io.File

internal class ScriptJobHandler : IJobHandler {

    override fun handle(jobContext: JobContext): JobResult {
        val scriptCacheDir = "scriptCache"
        File(scriptCacheDir).takeUnless { it.exists() }?.mkdir()

        val scriptType = jobContext.scriptType
        val scriptFile = "${scriptCacheDir}${File.separator}${jobContext.jobId}${scriptType!!.suffix}"
        File(scriptFile).writeText(jobContext.scriptSource!!)

        val process = ProcessBuilder(scriptType.exe, scriptFile).start()
        jobContext.process = process
        val exitCode = process.waitFor()
        val errorMessage = synchronized(jobContext.process!!) {
            process.errorStream.bufferedReader().use { it.readText() }
        }
        return if (exitCode == 0 && errorMessage.isBlank()) {
            JobResult.success()
        } else {
            JobResult.failed(message = errorMessage)
        }
    }
}